package models

import (
	"encoding/json"
	"gitee.com/liuziloong/ga1400gateway/config"
	"gitee.com/liuziloong/ga1400gateway/tools"
	"gitee.com/liuziloong/ga1400gateway/tools/logs"
	"time"
)

var deviceID = ""

//注册资源
func Register(requestBody []byte, host string) interface{} {
	//fmt.Printf("%s register数据：%s\n", time.Now().Format("2006-01-02 15:04:05"), string(requestBody))
	logs.BeeLogger.Info("HTTP 1400 registerHandle body:%s", string(requestBody))
	registerData := registerPacket{}
	err := json.Unmarshal(requestBody, &registerData)
	if err != nil {
		logs.BeeLogger.Error("registerHandle ---> json.Unmarshal() error:%s", err)
		return nil
	}

	if deviceID == "" {
		registerDataReply := &registerPacketReply{ResponseStatusObject: responseStatusObject{
			RequestURL:   tools.StringsJoin("http://", host, "/VIID/Register"),
			StatusCode:   1,
			StatusString: "OtherError",
			Id:           registerData.RegisterObject.DeviceID,
			LocalTime:    time.Now().Format("20060102150405"),
		}}

		deviceID = registerData.RegisterObject.DeviceID

		return registerDataReply
	}

	registerDataReply := &registerPacketReply{ResponseStatusObject: responseStatusObject{
		RequestURL:   tools.StringsJoin("http://", host, "/VIID/Register"),
		StatusCode:   0,
		StatusString: "正常",
		Id:           registerData.RegisterObject.DeviceID,
		LocalTime:    time.Now().Format("20060102150405"),
	}}

	return registerDataReply
}

//保活资源
func Keepalive(requestBody []byte, host string) interface{} {
	//fmt.Printf("%s keepalive数据：%s\n", time.Now().Format("2006-01-02 15:04:05"), string(requestBody))
	logs.BeeLogger.Debug("HTTP 1400 keepaliveHandle body:%s", string(requestBody))

	keepaliveData := keepalivePacket{}
	err := json.Unmarshal(requestBody, &keepaliveData)
	if err != nil {
		logs.BeeLogger.Error("keepaliveHandle ---> json.Unmarshal() error:%s", err)
		return nil
	}

	keepaliveDataReply := &keepalivePacketReply{ResponseStatusObject: responseStatusObject{
		RequestURL:   tools.StringsJoin("http://", host, "/VIID/Keepalive"),
		StatusCode:   0,
		StatusString: "正常",
		Id:           keepaliveData.KeepaliveObject.DeviceID,
		LocalTime:    time.Now().Format("20060102150405"),
	}}

	return keepaliveDataReply
}

//系统时间资源
func Time() interface{} {
	timeDataReply := &timePacketReply{SystemTimeObject: systemTimeObject{
		VIIDServerID: config.VIIDServerID,
		TimeMode:     "",
		LocalTime:    time.Now().Format("20060102150405"),
		TimeZone:     "",
	}}
	return timeDataReply
}
